package ahblue.cn.tanzi.ui.home.article;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;


import java.util.List;

import ahblue.cn.tanzi.R;
import ahblue.cn.tanzi.common.Config;
import ahblue.cn.tanzi.data.source.ApiCallback;
import ahblue.cn.tanzi.data.source.RemoteRepository;
import ahblue.cn.tanzi.model.home.ArticlesForCategory;
import ahblue.cn.tanzi.model.home.NewsForCategory;
import ahblue.cn.tanzi.ui.WebViewActivity;
import ahblue.cn.tanzi.ui.common.UIConfig;
import ahblue.cn.tanzi.util.GlideApp;
import ahblue.cn.tanzi.util.TimeUtils;
import ahblue.cn.tanzi.view.MyLinearLayoutManager;
import ahblue.cn.tanzi.view.decoration.SimpleItemDecoration;
import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 用于显示文章列表
 */
public class ArticleListFragment extends Fragment {

    private static final String ARG_CATEGORY_ID = "ARG_CATEGORY_ID";
    private static final String ARG_SOURCE      = "ARG_SOURCE";
    private static final String ARG_SEARCH_WORD = "ARG_SEARCH_WORD";
    private static final String ARG_CIRCLE_ID = "ARG_CIRCLE_ID";

    @BindView(R.id.recyclerViewArticleList)
    RecyclerView mRecyclerViewArticleList;
    @BindView(R.id.wv_circle_introduce)
    WebView wvCircleIntroduce;

    private int mArticleCategoryId;
    private String mSource;
    private String mSearchWord;
    private int mCircleId;

    private int mPage = 0;
    private final static int PAGE_COUNT = 10;
    private SimpleItemDecoration mSimpleItemDecoration;

    private MyLinearLayoutManager myLinearLayoutManager;

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param categoryId 文章分类ID.
     * @param source 来源，根据此判断是否为搜索.
     * @param searchWord 搜索关键字.
     * @return A new instance of fragment ArticleListFragment.
     */
    public static ArticleListFragment newInstance(int categoryId, String source, String searchWord,int circleId) {
        ArticleListFragment fragment = new ArticleListFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_CATEGORY_ID, categoryId);
        args.putInt(ARG_CIRCLE_ID, circleId);
        args.putString(ARG_SOURCE, source);
        args.putString(ARG_SEARCH_WORD, searchWord);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mArticleCategoryId = getArguments().getInt(ARG_CATEGORY_ID);
            mSource = getArguments().getString(ARG_SOURCE);
            mSearchWord = getArguments().getString(ARG_SEARCH_WORD);
            mCircleId = getArguments().getInt(ARG_CIRCLE_ID);

        }
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_article_list, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        if (1 == mArticleCategoryId){
            wvCircleIntroduce.setVisibility(View.VISIBLE);
            mRecyclerViewArticleList.setVisibility(View.GONE);

        }else {
            wvCircleIntroduce.setVisibility(View.GONE);
            mRecyclerViewArticleList.setVisibility(View.VISIBLE);
        }
        myLinearLayoutManager = new MyLinearLayoutManager(getContext());
        myLinearLayoutManager.setScrollEnabled(false);
        mRecyclerViewArticleList.setLayoutManager(myLinearLayoutManager);

        mRecyclerViewArticleList.setFocusableInTouchMode(false);
        mRecyclerViewArticleList.requestFocus();
        initData();
    }

    public void setSearchWord(String mSearchWord) {
        this.mSearchWord = mSearchWord;
        initData();
    }

    private void initData() {
        RemoteRepository repo = RemoteRepository.getsInstance();
        if (1 == mArticleCategoryId){
            wvCircleIntroduce.setHorizontalScrollBarEnabled(false);
            wvCircleIntroduce.loadUrl(Config.baseUrl + "/big_shot_circle_introduce?id=" + mCircleId);
        }else if(mArticleCategoryId == 2){
            repo.getNewsList(mSearchWord,newsForCategoryCallback);
        }else {
            repo.getBigShotArticleList(mArticleCategoryId, mPage, PAGE_COUNT, 0, mSearchWord, mArticleForCategoryCallback);
        }

    }

    /**
     * 获取某个分类下文章的回调函数。
     */
    ApiCallback<List<ArticlesForCategory>> mArticleForCategoryCallback = new ApiCallback<List<ArticlesForCategory>>() {

        @Override
        public void onSuccess(List<ArticlesForCategory> data) {
            if (getActivity() == null || getActivity().isFinishing()) {
                return;
            }
            ArticlesForCategoryAdapter adapter = new ArticlesForCategoryAdapter(data);
            adapter.setOnItemClickListener(mArticleOnClickListener);

            mRecyclerViewArticleList.setAdapter(adapter);
            if (mSimpleItemDecoration != null) {
                mRecyclerViewArticleList.removeItemDecoration(mSimpleItemDecoration);
            }
            mRecyclerViewArticleList.addItemDecoration(mSimpleItemDecoration = new SimpleItemDecoration(getContext()));
        }

        @Override
        public void onFailed(String errorMsg) {
            if (getActivity() == null || getActivity().isFinishing()) {
                return;
            }
            Toast.makeText(ArticleListFragment.this.getContext(), errorMsg, Toast.LENGTH_LONG).show();
        }
    };

/*    ApiCallback<String> mBigShotCircleIntroduceCallback = new ApiCallback<String>() {

        @Override
        public void onSuccess(String data) {
            Log.e("kzg","********************onSuccess:"+data);
            htmlText.setHtml(data,
                    new HtmlHttpImageGetter(htmlText));
        }

        @Override
        public void onFailed(String errorMsg) {
            Log.e("kzg","********************errorMsg:"+errorMsg);
            Toast.makeText(ArticleListFragment.this.getContext(), errorMsg, Toast.LENGTH_LONG).show();
        }
    };*/

    /**
     * 文章列表的adapter
     */
    class ArticlesForCategoryAdapter extends BaseQuickAdapter<ArticlesForCategory, BaseViewHolder> {

        ArticlesForCategoryAdapter(@Nullable List<ArticlesForCategory> data) {
            super(R.layout.item_home_article, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, ArticlesForCategory item) {
            ImageView iv = helper.getView(R.id.iv_news_cover);
            GlideApp.with(iv).load(item.image)
                    .placeholder(R.drawable.user_default_avatar)
                    .error(R.drawable.user_default_avatar)
                    .into(iv);

            helper.setText(R.id.tv_news_title, item.title);
            helper.setText(R.id.tv_news_author, item.user_name);
            helper.setText(R.id.tv_news_time, TimeUtils.getStandardDate(item.release_time));
            helper.setText(R.id.tv_read_count, "阅读 " + Integer.toString(item.read_count));
        }
    }

    BaseQuickAdapter.OnItemClickListener mArticleOnClickListener = new BaseQuickAdapter.OnItemClickListener() {
        @Override
        public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
            ArticlesForCategory article = (ArticlesForCategory) adapter.getData().get(position);
            final Intent intent = new Intent(ArticleListFragment.this.getContext(), ArticleDetailActivity.class);
            intent.putExtra(ArticleDetailActivity.ARG_ARTICLE_ID, article.id);
            intent.putExtra(ArticleDetailActivity.ARG_ARTICLE_TITLE, article.title);

            ArticleListFragment.this.startActivity(intent);
        }
    };

    public void setCanScrollable(boolean canScrollable){
        myLinearLayoutManager.setScrollEnabled(canScrollable);
    }

    /**
     * 获取新闻的回调函数。
     */
    ApiCallback<List<NewsForCategory>> newsForCategoryCallback = new ApiCallback<List<NewsForCategory>>() {

        @Override
        public void onSuccess(List<NewsForCategory> data) {
            if (getActivity() == null || getActivity().isFinishing()) {
                return;
            }
            NewsForCategoryAdapter adapter = new NewsForCategoryAdapter(data);
            adapter.setOnItemClickListener(mNewsOnClickListener);

            mRecyclerViewArticleList.setLayoutManager(new LinearLayoutManager(getContext()));
            mRecyclerViewArticleList.setAdapter(adapter);
            if (mSimpleItemDecoration != null) {
                mRecyclerViewArticleList.removeItemDecoration(mSimpleItemDecoration);
            }
            mRecyclerViewArticleList.addItemDecoration(mSimpleItemDecoration = new SimpleItemDecoration(getContext()));
        }

        @Override
        public void onFailed(String errorMsg) {
            if (getActivity() == null || getActivity().isFinishing()) {
                return;
            }
            Toast.makeText(ArticleListFragment.this.getContext(), errorMsg, Toast.LENGTH_LONG).show();
        }
    };

    /**
     * 新闻列表的adapter
     */
    class NewsForCategoryAdapter extends BaseQuickAdapter<NewsForCategory, BaseViewHolder> {

        NewsForCategoryAdapter(@Nullable List<NewsForCategory> data) {
            super(R.layout.item_home_article, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, NewsForCategory item) {
            ImageView iv = helper.getView(R.id.iv_news_cover);
            GlideApp.with(iv).load(item.thumbnail_pic_s)
                    .placeholder(R.drawable.user_default_avatar)
                    .error(R.drawable.user_default_avatar)
                    .into(iv);

            helper.setText(R.id.tv_news_title, item.title);
            helper.setText(R.id.tv_news_author, item.author_name);
            helper.setText(R.id.tv_news_time, item.date);
            //helper.setText(R.id.tv_read_count, "阅读 " + Integer.toString(item.read_count));
            helper.setVisible(R.id.tv_read_count,false);
        }
    }

    BaseQuickAdapter.OnItemClickListener mNewsOnClickListener = new BaseQuickAdapter.OnItemClickListener() {
        @Override
        public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
            NewsForCategory article = (NewsForCategory) adapter.getData().get(position);
            final Intent intent = new Intent(ArticleListFragment.this.getContext(), WebViewActivity.class);
            intent.putExtra(ArticleDetailActivity.ARG_ARTICLE_ID, article.url);

            ArticleListFragment.this.startActivity(intent);
        }
    };
}
